package utils

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// Response 通用API响应结构
type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Time int64  `json:"time"`
	Data any    `json:"data"`
}

// Success 返回成功响应
func Success(data any) *Response {
	return &Response{
		Code: 1,
		Msg:  "",
		Time: time.Now().Unix(),
		Data: data,
	}
}

// Fail 返回失败响应
func Fail(msg string) *Response {
	return &Response{
		Code: 0,
		Msg:  msg,
		Time: time.Now().Unix(),
		Data: nil,
	}
}

// FailWithCode 返回带有自定义错误码的失败响应
func FailWithCode(code int, msg string) *Response {
	return &Response{
		Code: code,
		Msg:  msg,
		Time: time.Now().Unix(),
		Data: nil,
	}
}

// CustomResponse 创建自定义响应
func CustomResponse(code int, msg string, data any) *Response {
	return &Response{
		Code: code,
		Msg:  msg,
		Time: time.Now().Unix(),
		Data: data,
	}
}

// JSON 向客户端发送JSON响应
func (r *Response) JSON(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, r)
}

// JSONWithStatus 向客户端发送指定HTTP状态码的JSON响应
func (r *Response) JSONWithStatus(ctx *gin.Context, httpStatus int) {
	ctx.JSON(httpStatus, r)
}
